package com.example.demo.dao;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.data.domain.Pageable;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.util.Map;

/**
 *  Hibernate分页处理类
 *  
 * @author jqlin
 *
 * @param <T>
 */
public class HibernateLimitationHandler<T> implements HibernateCallback<T> {

    private final String hql;

    private final Map<String, ?> params;

    private final int offset;

    private final int rowCount;

    public HibernateLimitationHandler(String hql, Map<String, ?> params, int offset, int rowCount) {
        this.hql = hql;
        this.params = params;
        this.offset = offset;
        this.rowCount = rowCount;
    }

    @Override
    public T doInHibernate(Session session) throws HibernateException {
        Query query = session.createQuery(hql);
        for (Map.Entry<String, ?> param : params.entrySet()) {
            query.setParameter(param.getKey(), param.getValue());
        }
        query.setFirstResult(offset);
        query.setMaxResults(rowCount);
        return (T) query.list();
    }
}
